<?
require_once('DataMediatorField.php');
require_once('DataMediatorModel.php');
require_once('ri/converter/ConverterFactory.php');
require_once('ri/validator/ValidatorFactory.php');

/**
 * Manages a list of locale aware converters and validators.
 */
class DataMediator {
	private $list,$fields= array();

	public function __construct(&$array) {
		// cast array to model
		if (is_array($array)) {
			require_once('DataMediatorArray.php');
			$this->list= new DataMediatorArray($array);
		}
		// assign model
		else if ($array instanceof DataMediatorModel)
			$this->list= $array;
		else
			throw new UnexpectedValueException('DefinedValueFacade needs a DefinedValueList object or an array to work.');
	}

	// CONVERTER
	public function setConverter($fieldName,$converter) {
		// cast to Converter
		if (!$converter instanceof Converter)
			$converter= ConverterFactory::forName($converter);

		$this->fields[$fieldName]= new DataMediatorField(
			$this->list,
			$fieldName,
			$converter
		);
		return $converter;
	}
	public function getConverter($fieldName) {
		return $this->getField($fieldName)->getConverter();
	}

	// VALIDATION
	public function addValidator($fieldName,$validator) {
		// cast to Validator
		if (!$validator instanceof Validator)
			$validator= ValidatorFactory::forName($validator);
		$this->getField($fieldName)->addValidator($validator);
		return $validator;
	}
	public function getErrors($fieldName=null) {
		$errors= array();
		if (empty($fieldName)) {
			foreach ($this->fields as $field)
				$errors= array_merge($errors,$field->getErrors());
		}
		else
			$errors= $this->getField($fieldName)->getErrors();
		return $errors;
	}
	
	public function isValid($fieldName=null) {
		if (empty($fieldName)) {
			foreach ($this->fields as $field)
				if (!$field->isValid()) return false;
		}
		else
			return $this->getField($fieldName)->isValid();
		return true;
	}
	
	// FIELDS
	public function getFields() {
		return $this->fields;
	}
	public function getField($fieldName) {
		if (empty($this->fields[$fieldName]))
			throw new InvalidArgumentException('Field must be initialised with a converter first. Call "setConverter(\''.$fieldName.'\',$converter);" before adding a validator or retrieving a field value.');
		return $this->fields[$fieldName];
	}
	
	// VALUES
	public function getAsString($fieldName) {
		return $this->getField($fieldName)->getAsString();
	}
	public function getAsDatatype($fieldName) {
		return $this->getField($fieldName)->getAsDatatype();
	}
}
